﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using KTDictSeg;
using FTAlgorithm;

namespace CoolCode.Search
{
	/// <summary>
	/// 分词结果
	/// </summary>
	public class SegmentResult : List<string>
	{ 
	}

	/// <summary>
	/// 分词引擎
	/// </summary>
	public class SegmentEngine : ISegmentEngine
	{
		internal CSimpleDictSeg SimpleDictSeg = null;

		public SegmentEngine()
		{
		}

		public SegmentEngine(string settingFile)
		{
			LoadDict(settingFile);
		}

		public void LoadDict(string settingFile)
		{
			try
			{
				SimpleDictSeg = new CSimpleDictSeg();
				SimpleDictSeg.LoadConfig(settingFile);
				/*Update in Jun 29, 2009 - SimpleDictSeg里获取绝对路径的方法在某些服务器下不正确*/
				//string currentPath = settingFile.GetParentPath();
				// if (SimpleDictSeg.DictPath.IsRelativePath())
				//SimpleDictSeg.DictPath = System.IO.Path.Combine(currentPath, SimpleDictSeg.DictPath);
				// if (SimpleDictSeg.LogFileName.IsRelativePath())
				//SimpleDictSeg.LogFileName = System.IO.Path.Combine(currentPath, SimpleDictSeg.LogFileName);
				SimpleDictSeg.LoadDict();
			}
			catch (Exception e)
			{
				SimpleDictSeg = null;
				throw new Exception(String.Format("Load Segment Dictionary Fail! Error Message:{0}", e.Message));
			}
		}

		public SegmentResult Parse(string text)
		{
			SegmentResult result = new SegmentResult();
			List<T_WordInfo> words = SimpleDictSeg.SegmentToWordInfos(text);
			var sortWords = words.Where(c => c != null).OrderByDescending(c => c.Rank).ThenByDescending(c => c.Position);
			/*去掉重复的值*/
			var filterWords = sortWords.Select(c => c.Word).Distinct();
			result.AddRange(filterWords);
			return result;
		}

	}
}
